// page/details/pages/referralCode/referralCode.js
const utils = require('../../../../utils/util.js');
let myRequest = require('../../../../common/script/myRequest.js');
let api = require('../../../../common/script/api.js');
let login = require('../../../../common/script/login');
const app = getApp();
Page({

  /**
   * 页面的初始数据
   */
  data: {
    formData: {
      phone: '请选择手机号码',
      phone_sign: "",
      name: ''
    },
    recode: null,
    recodeImg: '',
    recommendStatus: false,
    lat: '',
    lng: '',
    shopName: '请选择店铺',
    provinceName: '请选择省',
    province_code: '',
    shopList: [],
    provinceList: [],
    shopListData: [],
    provinceListData: [],
    org_code: "",
  },
  getData() {
    let that = this;
    let data = {
      type: 1,
      token: wx.getStorageSync('token'),
    }
    wx.showLoading({
      title: '加载中...',
    })
    myRequest.EasyHttp.post(api.reqUrls.getRecommendCode, data).then(res => {
      wx.hideLoading();
      //已申请
      if (res.data.status == 1) {
        that.setData({
          recommendStatus: true,
          recode: res.data.result.recode,
          recodeImg: res.data.result.img,
        })
        //未申请
      } else if (res.data.status == -2) {
        that.setData({
          recommendStatus: false,
        })
        that.getShop()
        // utils.getLocation().then(res => {
        //   that.getShop()
        // }).catch(err => {
        //   that.getShop({
        //     latitude: '',
        //     longitude: ''
        //   })
        //   console.log(err, 8888)
        //   that.setData({
        //     locationPermission: false
        //   })
        //   wx.showToast({
        //     title: "请授权位置权限"
        //   })

        // })
        // 需要补充
      } else if (res.data.status == -3) {
        that.setData({
          recommendStatus: false,
          'formData.phone': res.data.result.recode.phone,
          'formData.phone_sign': res.data.result.recode.phone_sign,
          'formData.name': res.data.result.recode.name,
        })
        that.getShop()
        // utils.getLocation().then(res => {
        //   that.getShop(res)
        // }).catch(err => {
        //   that.getShop({
        //     latitude: '',
        //     longitude: ''
        //   })
        //   console.log(err, 8888)
        //   that.setData({
        //     locationPermission: false
        //   })
        //   wx.showToast({
        //     title: "请授权位置权限"
        //   })

        // })
      }
    })

  },
  getShop() {
    const that = this;
    let data = {
      orgcode: that.data.orgcode,
      token: wx.getStorageSync('token')
    }
    wx.showLoading({
      title: '加载中...',
    })
    myRequest.EasyHttp.post(api.reqUrls.getRecommendShopList, data).then(res => {
      console.log(res,222222)
      wx.hideLoading();
      if (res.data.status == 1) {
        let provinceList = []
        let shopList = []
        let provinceListData = []
        let shopListData = []
        res.data.result.forEach((prop, index) => {
          if (prop.province_info.select == 1) {
            that.setData({
              provinceName: prop.province_info.province_name,
              province_code: prop.province_info.province_code,
              provinceIndex: index,
              shopName: prop.store_list[0].name,

            })
            prop.store_list.forEach((item, indexs) => {
              if (item.select == 1) {
                that.setData({
                  shopName: item.name,
                  orgIndex: indexs,
                  org_code: item.erp_store_code
                })
              }
              shopList.push(item.name)
              shopListData.push({
                name: item.name,
                code: item.erp_store_code
              })
            })
          }
          provinceList.push(
            prop.province_info.province_name
          )
          provinceListData.push({
            name: prop.province_info.province_name,
            code: prop.province_info.province_code,
          })
        })
        that.setData({
          provinceList,
          shopList,
          provinceListData,
          shopListData,
          shopData: res.result
        })
      }
    })
  },
  // 获取手机号
  getPhoneNumber(e) {
    const that = this;
    if (e.detail.errMsg == "getPhoneNumber:ok") {
      wx.login({
        success: function (res) {
          if (res.errMsg == "login:ok") {
            let data = {
              token: wx.getStorageSync('token'),
              encryptedData: e.detail.encryptedData,
              iv: e.detail.iv,
              code: res.code
            }
            wx.showLoading({
              title: '加载中...',
            })
            myRequest.EasyHttp.post(api.reqUrls.getMiniPhoneNoBind, data).then(res => {
              wx.hideLoading();
              if (res.data.status == 1) {
                that.setData({
                  'formData.phone': res.data.result.mobile,
                  'formData.phone_sign': res.data.result.phone_sign
                })

              } else {
                wx.showModal({
                  content: res.data.msg,
                  showCancel: false,
                  confirmText: '我知道了',
                  confirmColor: '#ff5151',
                  success(e) {}
                })
              }
            })
          }
        }
      })

    }
  },
  // 获取用户名
  getName(e) {
    const that = this;
    that.setData({
      [`formData.name`]: e.detail.value
    })
  },
  Apply() {
    let that = this;
    wx.showModal({
      content: '是否提交申请推荐码?',
      success(prop) {
        if (prop.confirm) {
          if (!that.data.formData.phone_sign) {
            wx.showToast({
              title: '请选择手机号码',
              icon: 'none',
              duration: 1000
            })
            return;
          }
          if (!that.data.formData.name) {
            wx.showToast({
              title: '请填写用户名称',
              icon: 'none',
              duration: 1000
            })
            return;
          }
          let data = {
            type: 2,
            orgcode: that.data.org_code,
            token: wx.getStorageSync('token'),
            phone: that.data.formData.phone,
            phone_sign: that.data.formData.phone_sign,
            name: that.data.formData.name,
          }
          wx.showLoading({
            title: '加载中...',
          })
          myRequest.EasyHttp.post(api.reqUrls.getRecommendCode, data).then(res => {
            wx.hideLoading();
            if (res.data.status == 1) {
              that.setData({
                recommendStatus: res.data.status == 1 ? true : false,
                recode: res.data.result.recode,
                recodeImg: res.data.result.img
              })

            } else {
              wx.showModal({
                content: res.data.msg,
                showCancel: false,
                confirmText: '我知道了',
                confirmColor: '#ff5151',
                success(e) {}
              })
            }
          })
          console.log('用户点击确定')
        } else if (prop.cancel) {
          console.log('用户点击取消')
        }
      }
    })

  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    const that = this;
    if (options.scene) {
      let sceneObj = utils.parseQueryString(options.scene)
      that.setData({
        orgcode: sceneObj.orgcode
      })
    } else {
      let scene = decodeURIComponent(options.q)
      const url = scene.substring(scene.indexOf('?') + 1)
      const params = url.split('&')
        .reduce(function (acc, param) {
          const [key, value] = param.split('=');
          acc[key] = decodeURIComponent(value);
          return acc;
        }, {});
      console.log(params,123)
      let orgcode = params['orgcode'];
      that.setData({
        orgcode: orgcode
      })
    }

    login.checkLogin().then(res => {
      that.getData()
    }).catch(err => {
      app.appCallBack = (e) => {
        that.getData()
      }
    })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  // onShareAppMessage() {

  // }
})